<template>
  <div class="data-filling">
    <el-tabs v-model="activeTab" @tab-change="handleTabClick">
      <el-tab-pane label="大学科技园数据填报" name="sciencePark">
        <div class="application-card" v-if="scienceParkData.length > 0">
          <el-card v-for="item in scienceParkData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>填报信息</span>
                <div class="card-actions">
                  <el-button  type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'sciencePark')">打印</el-button>
                  <!-- 状态为0时显示编辑和删除按钮 -->
                  <el-button v-if="item.status === 0" type="primary" link @click="handleEdit(item, 'sciencePark')">编辑</el-button>
                  <el-button v-if="item.status === 0" type="danger" link @click="handleDelete(item.id, 'sciencePark')">删除</el-button>
                  <!-- 状态为1时显示撤回和删除按钮 -->
                  <el-button v-if="item.status === 1" type="primary" link @click="handleWithdraw(item, 'sciencePark')">撤回</el-button>
<!--                  <el-button v-if="item.status === 1" type="danger" link @click="handleDelete(item.id, 'sciencePark')">删除</el-button>-->
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.enterpriseName }}</span>
              </div>
              <div class="info-item">
                <span class="label">填报时间：</span>
                <span class="value">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无填报记录" />
      </el-tab-pane>

      <el-tab-pane label="众创空间数据填报" name="innovationSpace">
        <div class="application-card" v-if="innovationSpaceData.length > 0">
          <el-card v-for="item in innovationSpaceData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>填报信息</span>
                <div class="card-actions">
                  <el-button type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'innovationSpace')">打印</el-button>
                  <!-- 状态为0时显示编辑和删除按钮 -->
                  <el-button v-if="item.status === 0" type="primary" link @click="handleEdit(item, 'innovationSpace')">编辑</el-button>
                  <el-button v-if="item.status === 0" type="danger" link @click="handleDelete(item.id, 'innovationSpace')">删除</el-button>
                  <!-- 状态为1时显示撤回和删除按钮 -->
                  <el-button v-if="item.status === 1" type="primary" link @click="handleWithdraw(item, 'innovationSpace')">撤回</el-button>
<!--                  <el-button v-if="item.status === 1" type="danger" link @click="handleDelete(item.id, 'innovationSpace')">删除</el-button>-->
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.companyName }}</span>
              </div>
              <div class="info-item">
                <span class="label">填报时间：</span>
                <span class="value">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无填报记录" />
      </el-tab-pane>
      <el-tab-pane label="孵化器年度数据填报" name="HatchYear">
        <div class="application-card" v-if="HatchYearData.length > 0">
          <el-card v-for="item in HatchYearData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>填报信息</span>
                <div class="card-actions">
                  <el-button  type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'HatchYear')">打印</el-button>
                  <!-- 状态为0时显示编辑和删除按钮 -->
                  <el-button v-if="item.status === 0" type="primary" link @click="handleEdit(item, 'HatchYear')">编辑</el-button>
                  <el-button v-if="item.status === 0" type="danger" link @click="handleDelete(item.id, 'HatchYear')">删除</el-button>
                  <!-- 状态为1时显示撤回和删除按钮 -->
                  <el-button v-if="item.status === 1" type="primary" link @click="handleWithdraw(item, 'HatchYear')">撤回</el-button>

                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.companyName }}</span>
              </div>
              <div class="info-item">
                <span class="label">填报时间：</span>
                <span class="value">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无填报记录" />
      </el-tab-pane>
      <el-tab-pane label="孵化器季度数据填报" name="HatchQuarter">
        <div class="application-card" v-if="HatchQuarterData.length > 0">
          <el-card v-for="item in HatchQuarterData" :key="item.id" class="mb-4">
            <template #header>
              <div class="card-header">
                <span>填报信息</span>
                <div class="card-actions">
                  <el-button  type="warning" v-if="item.status > 0" link @click="handleprint(item.id, 'HatchQuarter')">打印</el-button>
                  <!-- 状态为0时显示编辑和删除按钮 -->
                  <el-button v-if="item.status === 0" type="primary" link @click="handleEdit(item, 'HatchQuarter')">编辑</el-button>
                  <el-button v-if="item.status === 0" type="danger" link @click="handleDelete(item.id, 'HatchQuarter')">删除</el-button>
                  <!-- 状态为1时显示撤回和删除按钮 -->
                  <el-button v-if="item.status === 1" type="primary" link @click="handleWithdraw(item, 'HatchQuarter')">撤回</el-button>
                  <!--                  <el-button v-if="item.status === 1" type="danger" link @click="handleDelete(item.id, 'sciencePark')">删除</el-button>-->
                </div>
              </div>
            </template>
            <div class="card-content">
              <div class="info-item">
                <span class="label">企业名称：</span>
                <span class="value">{{ item.companyName }}</span>
              </div>
              <div class="info-item">
                <span class="label">填报时间：</span>
                <span class="value">{{ formatDate(item.createTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">状态：</span>
                <el-tag v-if="item.status === 0">未提交</el-tag>
                <el-tag type="primary" v-if="item.status === 1">已提交</el-tag>
                <el-tag type="success" v-if="item.status === 2">审核通过</el-tag>
                <el-tag type="danger" v-if="item.status === 3">审核失败</el-tag>
              </div>
            </div>
          </el-card>
        </div>
        <el-empty v-else description="暂无填报记录" />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { getMyDataSCienceList, getDatazongchuang,getDataHatchYear,getDataHatchQuarter, delDataSCience, delDatazongchuang,delDataHatchQuarter,delDataHatchYear, UpdataUserDataSCience, UpdataUserDatazongchuang,UpdataUserDataHatchQuarter,UpdataUserDataHatchYear } from '@/api/enterpeise';
import dayjs from "dayjs";

const router = useRouter();
const activeTab = ref('sciencePark');

// 列表数据
const scienceParkData = ref<any[]>([]);
const innovationSpaceData = ref<any[]>([]);
const HatchYearData = ref<any[]>([]);
const HatchQuarterData = ref<any[]>([]);
// 获取大学科技园数据填报列表
const getScienceParkList = async () => {
  try {
    const res = await getMyDataSCienceList();

    if (res.code === 200) {
      scienceParkData.value = Array.isArray(res.data) ? res.data : [];
      // console.log('获取大学科技园数据填报列表:'+JSON.stringify(res.data, null, 2))
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    ElMessage.error('获取大学科技园数据填报列表失败:', error);
  }
};

// 获取众创空间数据填报列表
const getInnovationSpaceList = async () => {
  try {
    const res = await getDatazongchuang();
    console.log(res.data);
    if (res.code === 200) {
      innovationSpaceData.value = Array.isArray(res.data) ? res.data : [];
      // console.log('获取众创空间数据填报列表:'+JSON.stringify(res.data, null, 2))
    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    console.error('获取众创空间数据填报列表失败:', error);
  }
};
// 获取孵化器年度数据填报列表
const getHatchYearList = async () => {
  try {
    const res = await getDataHatchYear();

    if (res.code === 200) {
      HatchYearData.value = Array.isArray(res.data) ? res.data : [];

    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    ElMessage.error('获取大孵化器年度数据填报列表失败:', error);
  }
};
// 获取孵化器季度数据填报列表
const getHatchQuarterList = async () => {
  try {
    const res = await getDataHatchQuarter();

    if (res.code === 200) {
      HatchQuarterData.value = Array.isArray(res.data) ? res.data : [];

    } else {
      ElMessage.error({
        message: res.msg,
      });
    }
  } catch (error) {
    ElMessage.error('获取大孵化器季度数据填报列表失败:', error);
  }
};
// 处理标签页切换
const handleTabClick = () => {
  switch (activeTab.value) {
    case 'sciencePark':
      getScienceParkList();
      break;
    case 'innovationSpace':
      getInnovationSpaceList();
      break;
    case 'HatchYear':
      getHatchYearList();
      break;
    case 'HatchQuarter':
      getHatchQuarterList();
      break;
  }
};

// 编辑填报
const handleEdit = (row: any, type: string) => {
  switch (type) {
    case 'sciencePark':
      router.push(`/personal-center/fill-information/kjy-data-fill?id=${row.id}`);
      break;
    case 'innovationSpace':
      router.push(`/personal-center/fill-information/zhongchuang-data-fill?id=${row.id}`);
      break;
    case 'HatchYear':
      router.push(`/personal-center/fill-information/Hatch-Yeardata-fill?id=${row.id}`);
      break;
    case 'HatchQuarter':
      router.push(`/personal-center/fill-information/Hatch-quarterdata-fill?id=${row.id}`);
      break;
  }
};
// 打印填报
const handleprint = (id: any, type: string) => {
  switch (type) {
    case 'sciencePark':
      const scienceParkRoute = router.resolve({
        name: 'kjydataprint',
        query: {
          id,
        },
      });
      window.open(scienceParkRoute.href, '_blank'); // 使用 .href 属性
      break;
    case 'innovationSpace':
      const innovationSpaceRoute = router.resolve({
        name: 'zhongchuangdataprint',
        query: {
          id,
        },
      });
      window.open(innovationSpaceRoute.href, '_blank'); // 使用 .href 属性
      break;
    case 'HatchYear':
      const HatchYearRoute = router.resolve({
        name: 'hatchyeardataprint',
        query: {
          id,
        },
      });
      window.open(HatchYearRoute.href, '_blank'); // 使用 .href 属性
      break;
    case 'HatchQuarter':
      const HatchQuarterRoute = router.resolve({
        name: 'HatchquaterdataPrint',
        query: {
          id,
        },
      });
      window.open(HatchQuarterRoute.href, '_blank'); // 使用 .href 属性
      break;
  }
};
// 撤回操作
const handleWithdraw = async (item: any, type: string) => {
  try {
    await ElMessageBox.confirm('确定要撤回该填报吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    let res;
    const bigIntId = BigInt(item.id);
    const updateData = {
      id: bigIntId.toString(),
      status: 0 // 将状态更新为0（未提交）
    };

    switch (type) {
      case 'sciencePark':
        res = await UpdataUserDataSCience(updateData);
        break;
      case 'innovationSpace':
        res = await UpdataUserDatazongchuang(updateData);
        break;
      case 'HatchYear':
        res = await UpdataUserDataHatchYear(updateData);
        break;
      case 'HatchQuarter':
        res = await UpdataUserDataHatchQuarter(updateData);
        break;
    }

    if (res?.code === 200) {
      ElMessage.success('撤回成功');
      handleTabClick(); // 刷新列表
    } else {
      ElMessage.error(res?.msg || '撤回失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('撤回失败:', error);
      ElMessage.error('撤回失败');
    }
  }
};

// 删除填报
const handleDelete = async (id: string | number, type: string) => {
  try {
    await ElMessageBox.confirm('确定要删除该填报吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });

    let res;
    const bigIntId = BigInt(id);
    switch (type) {
      case 'sciencePark':
        res = await delDataSCience(bigIntId.toString());
        break;
      case 'innovationSpace':
        res = await delDatazongchuang(bigIntId.toString());
        break;
      case 'HatchYear':
        res = await delDataHatchYear(bigIntId.toString());
        break;
      case 'HatchQuarter':
        res = await delDataHatchQuarter(bigIntId.toString());
        break;
    }

    if (res?.code === 200) {
      ElMessage.success('删除成功');
      handleTabClick(); // 刷新列表
    } else {
      ElMessage.error(res?.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除填报失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 格式化时间
const formatDate = (date: string | number | Date | null | undefined) => {
  if (!date) return '';
  return dayjs(date).format('YYYY-MM-DD');
};

// 初始化
onMounted(() => {
  handleTabClick();
});
</script>

<style lang="scss" scoped>
.data-filling {
  width: 100%;
  padding: 20px;

  :deep(.el-tabs__content) {
    padding: 20px 0;
  }

  .application-card {
    max-width: 1000px;
    margin: 0 auto;

    .mb-4 {
      margin-bottom: 16px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .card-actions {
        display: flex;
        gap: 10px;
      }
    }

    .card-content {
      .info-item {
        margin-bottom: 16px;
        display: flex;
        align-items: center;

        &:last-child {
          margin-bottom: 0;
        }

        .label {
          width: 100px;
          color: #606266;
        }

        .value {
          color: #303133;
        }
      }
    }
  }
}
</style>
